package it.uniroma2.exp;

import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ImageBlurring {

	public static void main(String[] args) {
		if (args.length < 3) {
			System.out.println("Missing parameters (blur level, input directory, output directory)");
			return;
		}
		int blur = Integer.parseInt(args[0]);
		String base = args[1];
		String dest = args[2];
		File folder = new File(base);
		File destFolder = new File(dest);
		destFolder.mkdirs();
		for (File file : folder.listFiles()) {
			System.out.println("Blurring "+file);
			BufferedImage img = null;
			try {
				img = ImageIO.read(file);
				BufferedImage blurred = blur(img, blur);
				String destName = file.getName();
				destName = destName.substring(0, destName.indexOf("."))+"_blur"+blur+destName.substring(destName.indexOf("."));
				ImageIO.write(blurred, "png", new File(destFolder, destName));
			} 
			catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public static BufferedImage blur(BufferedImage bufferedImage, int n) {
		float kElem = 1f / (float) (n * n);
		float[] kVector = new float[n * n];
		for (int i = 0; i < kVector.length; i++)
			kVector[i] = kElem;
		Kernel kernel = new Kernel(n, n, kVector);
		BufferedImageOp op = new ConvolveOp(kernel);
		return op.filter(bufferedImage, null);
	}
}
